package com.crm.model.dto;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.Enum.DictionaryEnum;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CommonUtils;
import com.crm.model.entity.cluePoolManager.Clue;
import com.crm.model.entity.common.Dictionary;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.vo.cluePoolManager.ClueImportVO;
import com.crm.service.cluePoolManager.ClueDbService;
import com.crm.service.common.DictionaryDbService;
import com.crm.service.impl.cluePoolManager.ClueDbServiceImpl;
import com.crm.service.impl.common.DictionaryDbServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;

import java.math.BigDecimal;
import java.sql.Array;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author luojie
 * @date 2021/5/16 17:45
 */
@Slf4j
public class InsertClueCallable implements Callable<JSONObject> {

    private ClueDbService clueDbService;

    private DictionaryDbService dictionaryDbService;

    private List<ClueImportVO> list;

    private CountDownLatch begin;

    private CountDownLatch end;

    private Integer clueType;

    private Integer clueStatus;

    private String cluePoolId;

    public InsertClueCallable(List<ClueImportVO> list,CountDownLatch begin,CountDownLatch end,Integer clueType, Integer clueStatus, String cluePoolId,ClueDbService clueDbService,DictionaryDbService dictionaryDbService){
        this.list = list;
        this.begin = begin;
        this.end = end;
        this.clueType = clueType;
        this.clueStatus = clueStatus;
        this.cluePoolId = cluePoolId;
        this.clueDbService = clueDbService;
        this.dictionaryDbService = dictionaryDbService;
    }

    @Override
    public JSONObject call(){

        //导入数量
        int importNum = 0;
        //重复的行数
        List<Integer> repeatIdStr = new ArrayList();
        //失败行数
        List<Integer> importFailIdStr = new ArrayList();

        for (int i = 0; i < list.size(); i++) {
            try {

                //公司名称
                String companyName = list.get(i).getCompanyName();
                //统一社会信用代码
                String unifiedSocialCreditCode = list.get(i).getUnifiedSocialCreditCode();

                //线索类型：1-公有；2-私有
                if (clueType == 1) {

                    //添加公有池
                    //2、查询线索是否重复（联系人电话和统一社会信用代码同时唯一）
                    Boolean ClueIfRepeated = clueDbService.selectClueIfRepeated(companyName, unifiedSocialCreditCode);
                    if (!ClueIfRepeated) {
                        //拼凑线索model
                        Clue clue = addClueModel(list.get(i));
                        clue.setClueType(clueType);
                        //公有池线索状态是在池
                        clue.setClueState(clueStatus);
                        clue.setCluePoolPublicId(cluePoolId);

                        Boolean insertResult = clueDbService.insertClue(clue);
                        if (insertResult) {
                            //导入成功
                           importNum = importNum + 1;
                        } else {
                            //导入失败
                            importFailIdStr.add(i+2);
                        }

                    } else {
                        //线索已重复
                        repeatIdStr.add(i+2);
                    }
                } else {
                    //添加私有池
                    //2、查询线索是否重复（公司名称和统一社会信用代码同时唯一）
                    Boolean ClueIfRepeated = clueDbService.selectClueIfRepeated(companyName, unifiedSocialCreditCode);
                    if (!ClueIfRepeated) {
                        Clue clue = addClueModel(list.get(i));
                        clue.setClueType(clueType);
                        //私有池线索状态是已领取
                        clue.setClueState(clueStatus);
                        clue.setCluePoolPrivateId(cluePoolId);
                        Boolean insertResult = clueDbService.insertClue(clue);
                        if (insertResult) {
                            //导入成功
                            importNum = importNum + 1;
                        } else {
                            //导入失败
                            importFailIdStr.add(i+2);
                        }
                    } else {
                        //线索已重复
                        repeatIdStr.add(i+2);
                    }
                }
            } catch (Exception e) {
                //导入失败
                importFailIdStr.add(i+2);
                log.error("ClueImportServiceImpl importClue error:", e);
                e.printStackTrace();
            }
            end.countDown();
        }

        JSONObject result = new JSONObject();
        result.put("importNum",importNum);
        result.put("repeatIdStr",repeatIdStr);
        result.put("importFailIdStr",importFailIdStr);
        return result;
    }

    //拼凑线索model
    public Clue addClueModel(ClueImportVO clueImportVO) throws ParseException {
        //DictionaryDbService dictionaryDbService = new DictionaryDbServiceImpl();
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
        Clue clue = new Clue();
        clue.setClueId(CommonUtils.getGUID());
        clue.setClueNumber(CommonUtils.getGUID());
/*        clue.setContactPerson(clueImportVO.getContactPerson());
        clue.setContactPersonPhone(clueImportVO.getContactPersonPhone());*/
        clue.setContactPersonPhone("");
        clue.setCompanyName(clueImportVO.getCompanyName());
        /*        clue.setJob(clueImportVO.getJob());*/
        clue.setUnifiedSocialCreditCode(clueImportVO.getUnifiedSocialCreditCode());
        clue.setCompanyWebsite(clueImportVO.getCompanyWebsite());
        //注册资本

        BigDecimal registeredCapital = getIntegerFromStr(clueImportVO.getRegisteredCapital());
        clue.setRegisteredCapital(registeredCapital);

        clue.setOrganizationCode(clueImportVO.getOrganizationCode());
        clue.setLegalRepresentative(clueImportVO.getLegalRepresentative());
        clue.setEnterpriseExternalPhone(clueImportVO.getEnterpriseExternalPhone());
        clue.setEnterpriseExternalLandline(clueImportVO.getEnterpriseExternalLandline());
        clue.setBusinessScope(clueImportVO.getBusinessScope());
        //成立日期
        if(!"-".equals(clueImportVO.getRegistrationTime())){
            clue.setRegistrationTime(simpleDateFormat.parse(clueImportVO.getRegistrationTime()));
        }
        //注册号
        clue.setRegistrationNumber(clueImportVO.getRegistrationNumber());
        if(!"-".equals(clueImportVO.getInsuredNumber())){
            clue.setInsuredNumber(Integer.parseInt(clueImportVO.getInsuredNumber()));
        }

        clue.setCompanyEmail(clueImportVO.getEmail());
/*        clue.setWechat(clueImportVO.getWechat());
        clue.setRemark(clueImportVO.getRemark());*/
        clue.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
        clue.setCreatePeopleId(userAccount.getAccountId());
        clue.setCreateTm(new Date());
        clue.setUpdatePeopleId(userAccount.getAccountId());
        clue.setUpdateTm(new Date());
        //工商注册号
        clue.setBusinessRegistrationNumber(clueImportVO.getRegistrationNumber());
        //clue.setPaidInCapital(clueImportVO.getPaidInCapital());
        //纳税人识别号
        clue.setTaxpayerIdentificationNumber(clueImportVO.getTaxpayerIdentificationNumber());
        //登记机关
        //clue.setRegistrationAuthority(clueImportVO.getRegistrationAuthority());
        //核准日期
        //clue.setApprovedDate(clueImportVO.getApprovedDate());
        //成立日期存到注册日期里面
        /*        clue.setEstablishmentDate(clueImportVO.getEstablishmentDate());*/
        //进出口企业代码
        //clue.setImportAndExportEnterpriseCode(clueImportVO.getImportAndExportEnterpriseCode());
        clue.setCompanyAddress(clueImportVO.getCompanyAddress());
        //clue.setProvinceId(clueImportVO.getProvinceId());
        clue.setProvinceName(clueImportVO.getProvinceName());
        //clue.setCityId(clueImportVO.getCityId());
        clue.setCityName(clueImportVO.getCityName());
        //clue.setTag(clueImportVO.getTag());

        //性别
/*        if("男".equals(clueImportVO.getSex())){
            clue.setSex("0");
        }else if("女".equals(clueImportVO.getSex())){
            clue.setSex("1");
        }*/

        //线索评级
/*        if(!StringUtils.isBlank(clueImportVO.getRating())){
            Dictionary rating = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CLUE_RATING.getTypeCode(),clueImportVO.getRating());
            if(rating!=null){
                clue.setRating(Integer.parseInt(rating.getDictCode()));
            }
        }*/

        //线索来源
/*        if(!StringUtils.isBlank(clueImportVO.getSource())){
            Dictionary source = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CLUE_SOURCE.getTypeCode(),clueImportVO.getSource());
            if(source!=null){
                clue.setSource(source.getDictCode());
            }else {
                //来源设置其他
                clue.setSource("11");
            }
        }*/
        clue.setSource("11");
        //客户类别
/*        if(!StringUtils.isBlank(clueImportVO.getClientCategories())){
            Dictionary clientCategories = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CLIENT_CATEGORIES.getTypeCode(),clueImportVO.getClientCategories());
            if(clientCategories!=null){
                clue.setClientCategories(clientCategories.getDictCode());
            }
        }*/

        //客户级别
/*        if(!StringUtils.isBlank(clueImportVO.getClientLevel())){
            Dictionary clientLevel = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CLIENT_LEVEL.getTypeCode(),clueImportVO.getClientLevel());
            if(clientLevel!=null){
                clue.setClientLevel(clientLevel.getDictCode());
            }
        }*/

        //行业
        if (!StringUtils.isBlank(clueImportVO.getIndustry())) {
            Dictionary industry = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.INDUSTRY.getTypeCode(), clueImportVO.getIndustry());
            if (industry != null) {
                clue.setIndustry(industry.getDictCode());
            } else {
                clue.setIndustry("21");
            }
        }

        //公司规模
/*        if(clueImportVO.getCompanySize()!=null){
            if(0<clueImportVO.getCompanySize()||clueImportVO.getCompanySize()<20){
                clue.setCompanySize("1");
            }else if(20<=clueImportVO.getCompanySize()||clueImportVO.getCompanySize()<100){
                clue.setCompanySize("2");
            }else if(100<=clueImportVO.getCompanySize()||clueImportVO.getCompanySize()<500){
                clue.setCompanySize("3");
            }else if(500<=clueImportVO.getCompanySize()||clueImportVO.getCompanySize()<1000){
                clue.setCompanySize("4");
            }else if(1000<=clueImportVO.getCompanySize()||clueImportVO.getCompanySize()<10000){
                clue.setCompanySize("5");
            }else if(10000<clueImportVO.getCompanySize()){
                clue.setCompanySize("6");
            }
        }*/

        //公司类型
        if (!StringUtils.isBlank(clueImportVO.getCompanyType())) {
            Dictionary companyType = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.COMPANY_TYPE.getTypeCode(), clueImportVO.getCompanyType());
            if (companyType != null) {
                clue.setCompanyType(companyType.getDictCode());
            } else {
                clue.setCompanyType("22");
            }
        }

        //资本类型
/*        if (!StringUtils.isBlank(clueImportVO.getCapitalType())) {
            Dictionary capitalType = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.CAPITAL_TYPE.getTypeCode(), clueImportVO.getCapitalType());
            if (capitalType != null) {
                clue.setCapitalType(capitalType.getDictCode());
            } else {
                clue.setCapitalType("3");
            }
        }*/

        //企业状态
        if (!StringUtils.isBlank(clueImportVO.getEnterpriseState())) {
            Dictionary enterpriseState = dictionaryDbService.selectDictionaryByDicName(DictionaryEnum.ENTERPRISE_STATE.getTypeCode(), clueImportVO.getEnterpriseState());
            if (enterpriseState != null) {
                clue.setEnterpriseState(enterpriseState.getDictCode());
            } else {
                clue.setEnterpriseState("1");
            }
        }
        return clue;
    }

    public BigDecimal getIntegerFromStr(String str) {
        // 控制正则表达式的匹配行为的参数(小数)
        Pattern p = Pattern.compile("(\\d+\\.\\d+)");
        //Matcher类的构造方法也是私有的,不能随意创建,只能通过Pattern.matcher(CharSequence input)方法得到该类的实例.
        Matcher m = p.matcher(str);
        //m.find用来判断该字符串中是否含有与"(\\d+\\.\\d+)"相匹配的子串
        if (m.find()) {
            //如果有相匹配的,则判断是否为null操作
            //group()中的参数：0表示匹配整个正则，1表示匹配第一个括号的正则,2表示匹配第二个正则,在这只有一个括号,即1和0是一样的
            str = m.group(1) == null ? "" : m.group(1);
        } else {
            //如果匹配不到小数，就进行整数匹配
            p = Pattern.compile("(\\d+)");
            m = p.matcher(str);
            if (m.find()) {
                //如果有整数相匹配
                str = m.group(1) == null ? "" : m.group(1);
            } else {
                //如果没有小数和整数相匹配,即字符串中没有整数和小数，就设为空
                str = "";
            }
        }
        if(!StringUtils.isBlank(str)){
            return new BigDecimal(str);
        }else {
            return new BigDecimal(0.00);
        }

    }

    public String removeCharacters(String str){
        String value = HtmlUtils.htmlUnescape(str);
        System.out.println("html转义后----"+value);
        String regEx = "[`~!@#$%^&*()+=|{}:;\\\\[\\\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
        String rs = Pattern.compile(regEx).matcher(value).replaceAll("").trim();
        return rs;
    }
}
